home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1621 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to access memory allocated  in function
  5. Date: 15 Jan 1996 21:44:45 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan15164445@g7240065.bridge.bst.bls.com>
  8. References: <4ddbe3$so3@josie.abo.fi> <4deg9p$bdi@nntpd2.cxo.dec.com>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: Brian Hibbert's message of 15 Jan 1996 21:17:45 GMT
  11.  
  12. In article <4deg9p$bdi@nntpd2.cxo.dec.com> Brian Hibbert <b_hibbert@csc32.enet.dec.com> writes:
  13. : csundqvi@abo.fi (Christoffer Sundqvist) wrote:
  14. :>
  15. :> How can i access memory allocated dynamically in a function after i leave
  16. :> the function,
  17.  
  18. : int* sub() /* this version returns a pointer to the allocated memory */
  19. :    {
  20. :    return  (int*) malloc(sizeof(int));
  21.              ^^^^^^
  22. The cast is unnecessary in ANSI C and should be removed See FAQ section 7.7.
  23.  
  24. :    }
  25.  
  26. : If you are using a C++ compiler, you can use a version that is closer to 
  27. : your original code by using a reference to the main's pointer.  
  28.  
  29. : void sub (int& p)
  30. :    {
  31. :    p = (int*) malloc (sizeof(int));
  32. :    }
  33.  
  34. This is not really the approriate group for this - and its wrong.
  35. 'p' is just a reference to an int it needs to be a reference to a pointer
  36. to an int.
  37.  
  38. void
  39. sub(int*& p)
  40. {
  41.     p = (int*)malloc(sizeof(int));
  42. }
  43.  
  44. And in C++ the cast is necessary. ;')
  45.  
  46. Regards
  47.  
  48.    -A.
  49.  
  50. -- 
  51. | A.Champion                |
  52.